<?php
//
//  VictoryCMS - Content managment system and framework.
//  Copyright (C) 2009  Lewis Gunsch
//
//  This file is part of VictoryCMS.
//  
//  VictoryCMS is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  VictoryCMS is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with VictoryCMS.  If not, see <http://www.gnu.org/licenses/>.

/**
 * VictoryCMS - UserLogin
 * 
 * @license http://www.gnu.org/licenses/gpl.html
 * @author Lewis Gunsch
 * @package Deprecated
 */

/**
 * @deprecated This class will be removed in future versions!
 * 
 * @package Deprecated
 */
class UserLogin {

	/**
	 * Constants Used in this library.
	 **/
	// Login Constants //////////////////////////////////////////////////////////
	const USERNAME = "username";
	const LOGIN_POST = "username_field";
	const PASSWORD_POST = "password_field";
	const LOGOUT_POST = "logout_field";
	const LOGOUT_VALUE = "logout_field_value";
	const FORM_TO_POST = "form_to_post";


	/**
	 * This function returns the username of the currently logged on user,
	 * or returns null if if the user is not logged in yet.
	 **/
	public function getUsername() {
		
		if ( !empty($_SESSION[self::USERNAME]) ) {
			return $_SESSION[self::USERNAME];
		} else {
			return null;
		}
	}


	/**
	 * This function checks if the password for the user
	 * is correct or not.
	 * It returns true if the password
	 * is correct and false if not.
	 *
	 * @param username The username of the user
	 * @param password The password of the user in "uudecoded" format.
	 *
	 * @return True if password if correct and false if not.
	 **/
	private function checkPassword( $userName, $password ) {
		$db = VcmsDBFactory::createVcmsDb();
		
		$usernameCleaned = $db->cleanData($userName);
		$query = sprintf( "SELECT password FROM User WHERE user_name='%s'", $usernameCleaned );
		
		$db->runQuery($query);
		$row = $db->fetchRow();
		
		$decoded_password = convert_uudecode( $row["password"] );
		if ( $row ) {
			if ( $password == $decoded_password ) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
		$db->cleanUp();
	}


	/**
	 * This function checks if the user is logged in or logged out, and
	 * checks the users permission to view the page. It returns
	 * true if the user has logged in and has permission to view or false if not.
	 *
	 * NOTE: This function requires that the session be initialized befor the html tag.
	 *
	 * @param permissionLevel The permission level of this page
	 *
	 * @return True if user has logged in and false if not.
	 **/
	public function handlePermissions( $permissionLevel ) {

		if (! $permissionLevel instanceof Permission ) {
			throw new InvalidPermissionException();
		}
		
		// Check if the user is already logged in
		if ( (! empty($_SESSION[self::USERNAME])) && empty($_POST[self::LOGOUT_POST]) ) {
			
			$userPermissions = $this->getPermissionLevel();
			if ( $permissionLevel->comparePermission( $userPermissions ) == true) {// check user permission
				
				$_SESSION[self::FORM_TO_POST] = "loggedIn";
				return true;
			}
			$_SESSION[self::FORM_TO_POST] = "incorrectPermission";
			return false; // does not have permission to view

			// The user just posted the login form.
		} else if ( (! empty($_POST[self::LOGIN_POST])) &&
		(! empty($_POST[self::PASSWORD_POST])) && empty($_POST[self::LOGOUT_POST]) ) {
			
			$userId = trim($_POST[self::LOGIN_POST]);
			$password = $_POST[self::PASSWORD_POST];
			
			if ( $this->checkPassword( $userId, $password ) ) {
				
				$_SESSION[self::USERNAME] = $userId; // login
				$userPermissions = $this->getPermissionLevel();
				if ( $permissionLevel->comparePermission( $userPermissions ) == true ) { // check user permission
					$_SESSION[self::FORM_TO_POST] = "loggedIn";
					return true;
				}
				$_SESSION[self::FORM_TO_POST] = "incorrectPermission";
				return false; // does not have permission to view

				// wrong password!
			} else {
				
				unset( $_SESSION[self::USERNAME] );
				unset( $_SESSION[PASSWORD_SESSION] );
				unset( $_POST[self::LOGIN_POST] );
				unset( $_POST[self::LOGOUT_POST] );
				$_SESSION[self::FORM_TO_POST] = "incorrectPassword";
				return false;
			}

			// The user has just posted the logout form.
		} else if ( (! empty($_POST[self::LOGOUT_POST])) || (empty($_SESSION[self::USERNAME]))) {
			
			unset( $_SESSION[self::USERNAME] );
			unset( $_POST[self::LOGIN_POST] );
			unset( $_POST[self::PASSWORD_POST] );
			unset( $_POST[self::LOGOUT_POST] );
			unset( $_SESSION[self::FORM_TO_POST] );
			session_destroy();
			return false;
		}
	}


	/**
	 * This function returns the permission level of the user logged in.
	 *
	 * @return Permission permission level of the user logged in.
	 **/
	public function getPermissionLevel() {
		
		// Get the user data
		$db = VcmsDBFactory::createVcmsDb();
		$query = "SELECT permission FROM User WHERE user_name='%s'";
		$query = sprintf( $query, $_SESSION[self::USERNAME] );
		$db->runQuery($query);
		$row = $db->fetchRow();
		$permNum = $row["permission"];
		$db->cleanUp();
		
		$permission = new Permission($permNum);
		
		return $permission;
	}
	

	/**
	 * This function returns the form necessary for logging in
	 * or logging out.
	 *
	 * @param action The page this function is used on.
	 *
	 * @return The html of the form.
	 **/
	public function getLoginLogoutForm( $action ) {

		$form = "<form name='LoginLogout' action='". $action ."' method='POST'>\n";

		if ( empty($_SESSION[self::FORM_TO_POST]) ) {
			
			$form .= "<label for='".self::LOGIN_POST."Field'>Login:&nbsp;</label>";
			$form .= "<input type='text' name='". self::LOGIN_POST ."' id='".self::LOGIN_POST."Field' size='10'>\n";
			$form .= "<label for='".self::PASSWORD_POST."Field'>Password:&nbsp;</label>";
			$form .= "<input type='password' name='". self::PASSWORD_POST ."' id='".self::PASSWORD_POST."Field' size='10'>\n";
			$form .= "<input type='submit' value='Login'>\n";

		} else if ( $_SESSION[self::FORM_TO_POST] == "loggedIn" ) {
			
			$form .= "<input type='hidden' name='". self::LOGOUT_POST ."' value='". self::LOGOUT_VALUE ."'>\n";
			$form .= "<label for='logoutbutton'>Logged in as " . $_SESSION[self::USERNAME] . ".&nbsp;</label>\n";
			$form .= "<input id='logoutbutton' type='submit' value='Logout'>\n";

		} else if ( $_SESSION[self::FORM_TO_POST] == "incorrectPermission" ) {
			
			$form .= "<span style='color: #FF0000;'>You do not have permission to view this page!</span><br>";
			$form .= "<input type='hidden' name='". self::LOGOUT_POST ."' value='". self::LOGOUT_VALUE ."'>\n";
			$form .= "<label for='logoutbutton'>Logged in as " . $_SESSION[self::USERNAME] . ".&nbsp;</label>\n";
			$form .= "<input id='logoutbutton' type='submit' value='Logout'>\n";

		} else if ( $_SESSION[self::FORM_TO_POST] == "incorrectPassword" ) {
			
			$form .= "<span style='color: #FF0000;'>Incorrect username or password</span><br>";
			$form .= "<label for='".self::LOGIN_POST."Field'>Login:&nbsp;</label>";
			$form .= "<input type='text' name='". self::LOGIN_POST ."' id='".self::LOGIN_POST."Field' size='10'>\n";
			$form .= "<label for='".self::PASSWORD_POST."Field'>Password:&nbsp;</label>";
			$form .= "<input type='password' name='". self::PASSWORD_POST ."' id='".self::PASSWORD_POST."Field' size='10'>\n";
			$form .= "<input type='submit' value='Login'>\n";
		}

		$form .= "</form>\n";
		return $form;

	}

}
?>